﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace LabelPrintSystem
{
    public partial class FrmPowManage : Form
    {
        public FrmPowManage(clsUser aUser)
        {
            InitializeComponent();
            this.Text = "用户权限管理";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            m_sConnect = aUser.m_sConnect;
            this.m_User = aUser;
        }

        DataTable m_showTable;
        const string m_sTableName = "tb_User";
        string m_sConnect;
        string m_sLastCellValue = "";
        bool m_bAddFlag;
        clsUser m_User;

        private void FrmPowManage_Load(object sender, EventArgs e)
        {
            this.textPowerInfo.Text = clsPowerManage.getInfomation();//权限说明
            dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            ListFresh();
        }
        private void ListFresh()
        {//刷新dataGridView
            string sSql = string.Format("select [ID] as 序号, [UserID] as 员工号, [User] as  用户名, [Password] as 密码, [Power] as 权限, [Remark] as 备注" +
                            " from {0} where [UserID] <> '999999' order by ID asc", m_sTableName);
            m_showTable = MicroDBHelper.ExecuteDataTable(sSql, null, m_sConnect);
            if (m_showTable == null)
                return;
            dataGridView.DataSource = m_showTable;
        }

        private void btn_Del_Click(object sender, EventArgs e)
        {
            if (dataGridView.CurrentCell == null || dataGridView.CurrentCell.RowIndex == -1)
            {
                MessageBox.Show("请在列表中选择链路!", "错误");
                return;
            }

            string sProjectId = dataGridView[0, dataGridView.CurrentCell.RowIndex].Value.ToString();
            if (sProjectId == "")
            {
                MessageBox.Show("请在列表中选择链路!", "错误");
                return;
            }

            if (MessageBox.Show("是否确认删除!", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }
            string sSwitchId = dataGridView.CurrentRow.Cells[0].Value.ToString();
            string sqlComm = "";

            sqlComm = "delete from " + m_sTableName + " where [ID] = " + sSwitchId;
            if (MicroDBHelper.ExecuteNonQuery(sqlComm, null, m_sConnect) == -1)
            {
                MessageBox.Show("删除失败！");
            }
            else
            {
                MessageBox.Show("删除成功！");
            }
            //删除记录后重新刷新列表时也会进入此事件，导致进入修改,所以不能用重新加载数据源的方式。
            dataGridView.Rows.RemoveAt(dataGridView.CurrentCell.RowIndex);
        }

        private void dataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dataGridView.CurrentCell.ColumnIndex == 0)
            {
                MessageBox.Show("不能修改该单元格!", "错误");
                e.Cancel = true;
                return;
            }
        }

        private void dataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            m_sLastCellValue = dataGridView[dataGridView.CurrentCell.ColumnIndex, dataGridView.CurrentCell.RowIndex].Value.ToString();
        }

        private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        { //之所以要用这个事件而不是  CellValueChanged 事件，是因为要对数据的输入进行校验和回退
            if (e.ColumnIndex == 0)
            {//ID不处理
                return;
            }
            string sSql = "";
            string sModifyProjectID = dataGridView[0, e.RowIndex].Value.ToString();
            if (sModifyProjectID == "")
            {//没有方案ID的在修改内容时 //添加的信息标记
                if (e.FormattedValue.ToString().Trim() != "")
                {
                    m_bAddFlag = true;
                }
            }
            else
            {//进行修改 update
                if (e.ColumnIndex == 1)
                {
                    int iID = -1;
                    if (!int.TryParse(e.FormattedValue.ToString().Trim(), out iID))
                    {
                        MessageBox.Show("用户名ID 格式不正确，请更改！");
                        e.Cancel = true;
                        return;
                    }
                    sSql = string.Format("select count(*) as [count] from {0} where {1} = '{2}' and {3} <> {4}",
                                           m_sTableName,
                                           m_User.m_arrDbHead[1], e.FormattedValue.ToString().Trim(),
                                           m_User.m_arrDbHead[0], sModifyProjectID);
                    int iFind = (int)MicroDBHelper.ExecuteScalar(sSql, null, m_sConnect);
                    if (iFind >= 1)
                    {
                        MessageBox.Show("用户名ID " + e.FormattedValue.ToString().Trim() + "已经存在，请更改！");
                        e.Cancel = true;
                        return;
                    }
                }
                //大部分列不允许为空
                if (e.FormattedValue.ToString().Trim() == "" && e.ColumnIndex >= 1 && e.ColumnIndex <= dataGridView.Columns.Count)
                {
                    MessageBox.Show(dataGridView.Columns[e.ColumnIndex].HeaderText + " 不能为空！");
                    e.Cancel = true;
                    return;
                }
                if (e.ColumnIndex == 4)
                {
                    if (!CheckPowerInput(e.FormattedValue.ToString().Trim()))
                    {
                        m_bAddFlag = false;//必须要加这句，不然出现这个错误后，直接cancel时整行删除后，而标志位仍旧为添加，导致异常。
                        e.Cancel = true;
                        return;
                    }
                }
                if (e.FormattedValue.ToString().Trim() != m_sLastCellValue)
                {
                    sSql = string.Format("update {0} set {1} = '{2}' where ID = {3}",
                                         m_sTableName,
                                         m_User.m_arrDbHead[e.ColumnIndex],
                                         e.FormattedValue.ToString().Trim(),
                                         sModifyProjectID);
                    if (MicroDBHelper.ExecuteNonQuery(sSql, null, m_sConnect) != 1)
                    {
                        MessageBox.Show("修改失败！");
                        e.Cancel = true;
                        return;
                    }
                }
            }
            return;
        }

        private void dataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            dataGridView.Rows[e.RowIndex].ErrorText = "输入的数字格式不正确";
            MessageBox.Show("输入的格式不正确");
            e.Cancel = true;
        }

        private bool CheckPowerInput(string sPower)
        {//权限特殊处理
            int iPowerNew = 0;
            try
            {
                //iPowerNew = Convert.ToInt32(sPower);
                string[] lstPower = sPower.Split(',');
                foreach (var pow in lstPower)
                {
                    iPowerNew = Convert.ToInt32(pow);
                    if (iPowerNew > 999)
                    {
                        MessageBox.Show("不能大于自己的权限");
                        return false;
                    }
                }
            }
            catch
            {
                MessageBox.Show("输入的权限不合法");
                return false;
            }
            return true;
        }

        private void dataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 27)
            {//cancel
                m_bAddFlag = false;
            }
        }

        private void dataGridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            string sSql = "";
            StringBuilder sbValue = new StringBuilder(1);
            if (m_bAddFlag)
            {//进行添加处理

                //保存前数据合法性检查
                for (int i = 1; i < dataGridView.Columns.Count; i++)
                {
                    if (dataGridView[i, e.RowIndex].Value.ToString().Trim() == "")
                    {
                        MessageBox.Show(dataGridView.Columns[i].HeaderText + " 不能为空！");
                        m_bAddFlag = false;//必须要加这句，不然出现这个错误后，直接cancel时整行删除后，而标志位仍旧为添加，导致异常。
                        e.Cancel = true;
                        return;
                    }

                    if (i == 4)
                    {//权限特殊处理
                        if (!CheckPowerInput(dataGridView[i, e.RowIndex].Value.ToString().Trim()))
                        {
                            m_bAddFlag = false;//必须要加这句，不然出现这个错误后，直接cancel时整行删除后，而标志位仍旧为添加，导致异常。
                            e.Cancel = true;
                            return;
                        }
                    }
                }

                if (true) //if (e.ColumnIndex == 1)
                {
                    int iID = -1;
                    if (!int.TryParse(dataGridView[1, e.RowIndex].Value.ToString().Trim(), out iID))
                    {
                        MessageBox.Show("用户名ID 格式不正确，请更改！");
                        e.Cancel = true;
                        return;
                    }

                    //sSql = "select count(*) as [count] from tb_User where " + m_User.m_arrDbHead[1] + " = '" + dataGridView[1, e.RowIndex].Value.ToString().Trim() +"' " ;
                    sSql = string.Format("select count(*) as [count] from {0} where {1} = '{2}'",
                                         m_sTableName,
                                         m_User.m_arrDbHead[1],
                                         dataGridView[1, e.RowIndex].Value.ToString().Trim());
                    int iFind = (int)MicroDBHelper.ExecuteScalar(sSql, null, m_sConnect);
                    if (iFind >= 1)
                    {
                        MessageBox.Show("用户名ID " + dataGridView[1, e.RowIndex].Value.ToString().Trim() + "已经存在，请更改！");
                        e.Cancel = true;
                        return;
                    }
                }


                for (int i = 1; i < m_showTable.Columns.Count; i++)
                {
                    //if(i == 3){//权限特殊处理
                    //    sbValue.Append(dataGridView[i, e.RowIndex].Value.ToString().Trim());
                    //}
                    //else{
                    sbValue.Append("'");
                    sbValue.Append(dataGridView[i, e.RowIndex].Value.ToString().Trim());
                    sbValue.Append("'");
                    //}
                    if (i != m_showTable.Columns.Count - 1)
                    {
                        sbValue.Append(", ");
                    }
                }

                sSql = "insert into " + m_sTableName + " ( " + m_User.GetDbStr(1) + ") values (" + sbValue.ToString() + ")";
                if (MicroDBHelper.ExecuteNonQuery(sSql, null, m_sConnect) != 1)
                {
                    MessageBox.Show("添加失败！");
                    m_bAddFlag = false;
                    e.Cancel = true;
                    return;
                }
                else
                {//显示新的方案ID
                    m_bAddFlag = false;
                    int iID = Convert.ToInt32((decimal)MicroDBHelper.ExecuteScalar("SELECT IDENT_CURRENT('" + m_sTableName + "')", null, m_sConnect));
                    if (iID == -1)
                    {
                        iID = (int)MicroDBHelper.ExecuteScalar("SELECT top 1 ID from " + m_sTableName + " order by ID desc", null, m_sConnect);
                    }

                    dataGridView[0, dataGridView.CurrentCell.RowIndex].Value = iID;
                }
            }
        }
    }
}
